package org.kernely.test.todopage;

import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.kernely.persistence.service.SessionService;
import org.kernely.security.dao.UserDAO;
import org.kernely.security.dao.UserDetailsDAO;
import org.kernely.security.persistence.Role;
import org.kernely.security.persistence.User;
import org.kernely.security.persistence.UserDetails;
import org.kernely.test.dao.TodoDao;
import org.kernely.test.persistence.ToDo;
import org.kernely.test.testbundle.TestBundle;
import org.kernely.ui.mvp.IKernelyView;
import org.kernely.ui.mvp.KernelyPresenter;
import org.kernely.ui.utils.KernelyNotification;

import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;

/**
 * The ToDoPresenter class
 */
public class ToDoPresenter extends KernelyPresenter<ToDoView>{
	private static SessionService service;

	/**
	 * @see org.kernely.core.service.IKernelyPresenter#bind()
	 */
	@Override
	public final void bind() {
		
		// Fill the combo box with users logins
		UserDAO udao = new UserDAO();
		Set<User> list = udao.getUsers();
		for (User userItem : list){
			this.view.getUsers().addItem(userItem.getLogin());
		}
		// Adding a listener to the validate button
		this.view.getValidateButton().addListener(new ClickListener(){
			private static final long serialVersionUID = 7871219904239488944L;
			/**
			 * Called when a ClickEvent is fired
			 */
			public void buttonClick (Button.ClickEvent event) {
				registerTask();
			}
		});
		// Adding a listener to the drop table button
		this.view.getDropButton().addListener(new ClickListener(){
			private static final long serialVersionUID = 7871219904239488944L;
			/**
			 * Called when a ClickEvent is fired
			 */
			public void buttonClick (Button.ClickEvent event) {
				dropTable();
				listToDo();
			}
		});
		// Adding a listener to the refresh button
		this.view.getRefreshButton().addListener(new ClickListener(){
			private static final long serialVersionUID = 7871219904239488944L;
			/**
			 * Called when a ClickEvent is fired
			 */
			public void buttonClick (Button.ClickEvent event) {
				listToDo();
			}
		});
		
		listToDo();
	}
	
	/**
	 * Fill the table with all ToDoTasks registered
	 */
	public final void listToDo(){
		// Clean the table
		this.view.getTable().removeAllItems();
		//call the session factory to get all the messages
		UserDetailsDAO ud = UserDetailsDAO.getInstance();
		String username;
		UserDetails u;
		List<ToDo> messages = TodoDao.getInstance().getAll();
		User current = TestBundle.getSecurityService().getCurrentUser();
		int i = 0;
		for(ToDo message : messages){
			// Check if the user has the permission to see the message
			// Note : the admin can see all messages
			boolean isAdmin = TestBundle.getSecurityService().currentUserHasOneOf(Role.ROLE_ADMINISTRATOR);
			boolean hasPermission = TestBundle.getSecurityService().currentUserHasPermission("task:read:"+message.id);
			if(isAdmin || hasPermission){
				u = ud.getUserDetails(message.user);
				username = u.getFirstname() + " " + u.getName();
				this.view.getTable().addItem(new Object[] {message.id, message.text, username}, Integer.valueOf(i));
				i++;
			}
		}
	}
	
	/**
	 * Remove all elements stored in database table
	 */
	public final void dropTable(){
		 TodoDao.getInstance().deleteAll();
		 listToDo();
	}
	
	/**
	 * Save a ToDo Task and associates it permissions.
	 */
	private void registerTask(){
		if (this.view.getTaskTextField().toString() != "" && this.view.getTaskTextField().toString() != "null" && this.view.getTaskTextField().toString() != null){
			// Get the current user
			UserDAO udao = UserDAO.getInstance();
			User selected;
			// If no user specified, get the current user connected.
			if(this.view.getUsers().getValue() == null){
				// If no user is selected, set the ToDo user as the current user.
				selected = TestBundle.getSecurityService().getCurrentUser();
			}
			else{
				selected = udao.findUser(this.view.getUsers().getValue().toString());
			}
			ToDo msg = new ToDo();
			msg.text = this.view.getTaskTextField().toString();
			msg.user = selected;
			int id = TodoDao.getInstance().save(msg);
			// Associate a permission
			// We create the authorization string
			String authorization = "task:read:"+id;
			TestBundle.getSecurityService().grantAuthorization(selected, authorization);
			
			
			listToDo();
			// Reset the textField
			this.view.getTaskTextField().setValue("");
		} else {
			this.view.getWindow().showNotification(new KernelyNotification("You can't save empty tasks.",KernelyNotification.ERROR_ICON));
		}
	}
}
